package com.space.mygql.stitching.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * @author <a href="mailto:414563035@qq.com">Bedroom</a>
 * @date 2021/5/27 5:48 下午
 */
@Component
@Slf4j
public class InetUtil {
    public InetAddress findFirstNonLoopbackAddress() {
        InetAddress result = null;

        try {
            int lowest = 2147483647;
            Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();

            label61:
            while (true) {
                NetworkInterface ifc;
                while (true) {
                    do {
                        if (!nics.hasMoreElements()) {
                            break label61;
                        }

                        ifc = nics.nextElement();
                    } while (!ifc.isUp());

                    log.trace("Testing interface: " + ifc.getDisplayName());
                    if (ifc.getIndex() >= lowest && result != null) {
                        if (result != null) {
                            continue;
                        }
                        break;
                    }

                    lowest = ifc.getIndex();
                    break;
                }

                Enumeration<InetAddress> addrs = ifc.getInetAddresses();

                while (addrs.hasMoreElements()) {
                    InetAddress address = (InetAddress) addrs.nextElement();
                    if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
                        log.trace("Found non-loopback interface: " + ifc.getDisplayName());
                        result = address;
                    }
                }
            }
        } catch (IOException var8) {
            log.error("Cannot get first non-loopback address", var8);
        }

        if (result != null) {
            return result;
        } else {
            try {
                return InetAddress.getLocalHost();
            } catch (UnknownHostException var7) {
                log.warn("Unable to retrieve localhost");
                return null;
            }
        }
    }
}
